﻿using System.Collections.Generic;
using System.Linq;
using Inscriptionem.Models.Blog.Base;

namespace Inscriptionem.Models.Blog.Views
{
    public class BlogViewModel : BaseViewModel
    {
        protected readonly ORM.DB DB = new ORM.DB();

        public BlogViewModel()
        {
            Articles = new List<Article>();
        }

        #region Data
        protected ORM.Section SectionDataProvider
        {
            get
            {
                var language = DB.Languages.FirstOrDefault(l => l.Name.ToLower() == Language.ToLower()) ?? DB.Languages.First(l => l.IsDefault);

                return language.Sections.FirstOrDefault(s => (string.IsNullOrWhiteSpace(Section)) ? s.IsDefault : s.Name.ToLower() == Section.ToLower()) ??
                              language.Sections.FirstOrDefault(s => s.IsDefault);
            }
        }
        #endregion

        #region Collections
        public override IEnumerable<ORM.Category> Categories { get { return SectionDataProvider == null ? new List<ORM.Category>() : SectionDataProvider.Categories.AsEnumerable(); } }
        public override IEnumerable<ORM.Page> Pages { get { return SectionDataProvider == null ? new List<ORM.Page>() : SectionDataProvider.Pages.AsEnumerable(); } }
        public override IEnumerable<ORM.Tag> Tags
        {
            get
            {
                return SectionDataProvider == null ? new List<ORM.Tag>() :
                                                     Pages.SelectMany(p => p.PageTags).Select(pt => pt.Tag)
                                                     .Union(SectionDataProvider.Categories.SelectMany(s => s.PostCategories).Select(pc => pc.Post).SelectMany(p => p.PostTags).Select(pt => pt.Tag))
                                                     .Distinct().AsEnumerable();
            }
        }
        #endregion

        public string SectionLocalizedName { get { return SectionDataProvider == null ? string.Empty : SectionDataProvider.LocalizedName; } }

        #region Articles
        public List<Article> Articles { get; protected set; }
        #endregion
    }
}